package com.zou.music_downloader;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.widget.SearchView;

import com.android.volley.RequestQueue;
import com.google.gson.Gson;
import com.zou.music_downloader.bean.SimpleSearchSugestionEntity;
import com.zou.music_downloader.secondaryfragments.HotwordFragment;
import com.zou.music_downloader.secondaryfragments.HotwordFragment_;
import com.zou.music_downloader.secondaryfragments.ResultFragment;
import com.zou.music_downloader.secondaryfragments.ResultFragment_;
import com.zou.music_downloader.secondaryfragments.SugestionFragment;
import com.zou.music_downloader.secondaryfragments.SugestionFragment_;
import com.zou.music_downloader.utils.SharedPreferencesUtils;
import com.zou.music_downloader.utils.VolleyUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Search页面
 * Created by zou on 2016/3/11.
 */

@EFragment(R.layout.fragment_search)
public class SearchFragment extends android.support.v4.app.Fragment {


    String HOTWORD   = "HOTWORD"; //热词
    String SUGESTION = "SUGESTION"; //搜索建议
    String MERGE     = "MERGE"; //合并结果

    @ViewById
    public static SearchView searchview;

    public SugestionFragment mySuggestionFragment = SugestionFragment_.builder().build();
    public HotwordFragment   myHotwordFragment    = HotwordFragment_.builder().build();

    public ResultFragment myResultFragment = ResultFragment_.builder().build();


    private FragmentTransaction fragmentTransaction;
    private RequestQueue        queue;
    private Gson                gson;
    private FragmentManager     fragmentManager;


    @AfterViews
    void afterView() {


        fragmentManager = getFragmentManager();


//        初始化fragment
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.searchview_container, myHotwordFragment, HOTWORD)
                .add(R.id.searchview_container, mySuggestionFragment, SUGESTION).hide(mySuggestionFragment)
                .add(R.id.searchview_container, myResultFragment, MERGE).hide(myResultFragment).commitAllowingStateLoss();


        queue = VolleyUtil.getQueue(getContext());
        gson = new Gson();

        searchview.setIconifiedByDefault(false);
        searchview.setSubmitButtonEnabled(true);
        searchview.setQueryHint("搜索歌曲、歌手或专辑");


        searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            private String oldString = null;

            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!TextUtils.isEmpty(query)) {
                    trans(SUGESTION, MERGE);
                    myResultFragment.setData(query);
                }
                searchview.clearFocus();
                Log.d("wocao", "onQueryTextSubmit: " + searchview.hasFocus());
                Log.d("wocao", "onQueryTextSubmit: " + searchview.isFocused());
                oldString = null;

                //*********************************************************//
                //        sp存储的历史记录转换为list
                String searchedHistoryString = (String) SharedPreferencesUtils.getParam(getContext(), "history", "");
                Log.e("wocao", "onQueryTextSubmit: get" + searchedHistoryString);

                String[] strings = {};
                if (!TextUtils.isEmpty(searchedHistoryString)) {
                    strings = searchedHistoryString.split("\\|+");
                }
                final List<String> strings1 = new ArrayList<>();
                for (int i = 0; i < strings.length; i++) {
                    strings1.add(strings[i]);
                }


                if (strings1.contains(query)) {
                    strings1.remove(query);

                }
                strings1.add(0, query);

                StringBuffer newhistoryString = new StringBuffer();
                for (int i = 0; i < strings1.size(); i++) {
                    newhistoryString.append(strings1.get(i)).append("|");
                }
                SharedPreferencesUtils.setParam(getContext(), "history", newhistoryString.toString());
                Log.e("wocao", "onQueryTextSubmit: " + newhistoryString);
                myHotwordFragment.getSp();
                //*********************************************************//

                return true;
            }


            @Override
            public boolean onQueryTextChange(String newText) {
                final List<SimpleSearchSugestionEntity> datas = new ArrayList<SimpleSearchSugestionEntity>();
//                控制搜索建议的出现
                String newString = newText.trim();
                Log.d("wocao", "onQueryTextChange:" +
                        " t" + newText);
                Log.d("wocao", "onQueryTextChange: s" + newString);


                if (TextUtils.isEmpty(oldString) && !TextUtils.isEmpty(newString)) {
                    trans(HOTWORD, SUGESTION);
//                    myFragment = (SugestionFragment) fragmentManager.findFragmentByTag(SUGESTION);

                    Log.d("wocao", "onQueryTextChange: trans Suggestion");

                    // TODO: 2016/3/11 fragment间通信
                }


                if (TextUtils.isEmpty(newString)) {
                    trans(SUGESTION, HOTWORD);
                    Log.d("wocao", "onQueryTextChange: trans HotWord");
                } else {
                    mySuggestionFragment.setData(newString);
                }


                oldString = newString;
                return true;
            }
        });
    }

    //    切换fragment
    void trans(String oldTag, String newTag) {
        fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.hide(fragmentManager.findFragmentByTag(oldTag))
                .show(fragmentManager.findFragmentByTag(newTag));


/*
        if (tag == HOTWORD) {
            fragmentTransaction.replace(R.id.searchview_container, new HotwordFragment_(), tag);
        } else if (tag == SUGESTION) {
// TODO: 2016/3/11  搜索建议
            fragmentTransaction.replace(R.id.searchview_container, mySuggestionFragment);

        } else if (tag == MERGE) {
// TODO: 2016/3/11
        }
*/

        fragmentTransaction.commit();
    }


}
